package com.yokead.controller.sysadmin.user;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;
import com.yokead.common.UserUtil;
import com.yokead.common.base.AdminBaseControl;
import com.yokead.system.log.SystemLog;
import com.yokead.util.JsonUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @author jiangzeyin
 * @date 2018/5/10
 */
@Controller
@RequestMapping("sysadmin/user/")
public class UserInfoController extends AdminBaseControl {


    @RequestMapping(value = "list.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String userList() throws IOException {
        String filePath = Config.Admin.getUserConfigFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterator.next();
            String name = jsonObject.getString("name");
            if (name.endsWith("_del")) {
                iterator.remove();
            }
        }
        setAttribute("data", jsonArray);
        return "sysadmin/user/list";
    }

    @RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String edit(String id) throws IOException {
        if (!StringUtil.isEmpty(id)) {
            String filePath = Config.Admin.getUserConfigFile();
            JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
            if (jsonArray != null) {
                JSONObject jsonObject;
                for (Object object : jsonArray) {
                    jsonObject = (JSONObject) object;
                    String userId = jsonObject.getString("id");
                    if (userId.equals(id)) {
                        setAttribute("item", jsonObject);
                        break;
                    }
                }
            }
        }
        return "sysadmin/user/edit";
    }

    @RequestMapping(value = "save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save(String name, String pwd, String mark, String id) throws IOException {
        boolean update = !StringUtil.isEmpty(id);
        if (!update) {
            if (StringUtil.isEmpty(name, 2, 20)) {
                return JsonMessage.getString(400, "请输入2-20的登录名");
            }
            if (!Pattern.matches("^[0-9a-zA-Z_]+$", name)) {
                return JsonMessage.getString(400, "登录名只能是数字,字母或者 '_'");
            }
            if (name.contains("-")) {
                return JsonMessage.getString(401, "登录名不能包含中划线");
            }
            if (name.endsWith("_del")) {
                return JsonMessage.getString(401, "登录名不可用");
            }
        }
        if (!StringUtil.isEmpty(pwd)) {
            if (StringUtil.isEmpty(pwd, 4, 20)) {
                return JsonMessage.getString(400, "请输入4-20的位的密码");
            }
        }
        String manage = getParameter("manage");
        String filePath = Config.Admin.getUserConfigFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = UserUtil.getIterator();
        boolean find = false;
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            if (update) {
                String userId = jsonObject.getString("id");
                if (id.equals(userId)) {
                    if (!StringUtil.isEmpty(pwd)) {
                        jsonObject.put("pwd", pwd);
                    }
                    jsonObject.put("mark", mark);
                    jsonObject.put("manage", "on".equals(manage));
                    find = true;
                }
            } else {
                String userName = jsonObject.getString("name");
                if (name.equalsIgnoreCase(userName)) {
                    find = true;
                    break;
                }
                if ((name + "_del").equalsIgnoreCase(userName)) {
                    find = true;
                    break;
                }
            }
        }
        if (update) {
            if (!find) {
                return JsonMessage.getString(405, "修改失败，没有对应用户信息");
            }
        } else {
            if (find) {
                return JsonMessage.getString(405, "用户名已经存在啦");
            }
            JSONObject jsonObject = Config.Admin.getDefaultUser();
            String adminUser = jsonObject.getString("name");
            if (name.equalsIgnoreCase(adminUser)) {
                return JsonMessage.getString(405, "用户名已经存在啦!");
            }
        }
        if (!update) {
            JSONObject info = new JSONObject();
            info.put("id", UUID.randomUUID().toString());
            info.put("name", name);
            info.put("pwd", pwd);
            info.put("mark", mark);
            info.put("manage", "on".equals(manage));
            String path = Config.Nginx.getNginxConfigPath();
            File file = new File(path, name);
            if (!file.exists() && !file.mkdirs()) {
                return JsonMessage.getString(500, "创建用户目录异常");
            }
            SystemLog.LOG().info(userName + "添加：" + info.toJSONString());
            jsonArray.add(info);
        }
        JsonUtil.saveJson(filePath, jsonArray);
        //String newsJson = JsonUtil.formatJson(jsonArray.toString());
        //FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "");
    }

    @RequestMapping(value = "del_{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String del(@PathVariable String id) throws IOException {
        String filePath = Config.Admin.getUserConfigFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = jsonArray.iterator();
        boolean find = false;
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            String userId = jsonObject.getString("id");
            if (userId.equals(id)) {
                //iterable.remove();
                String name = jsonObject.getString("name");
                jsonObject.put("name", name + "_del");
                find = true;
                break;
            }
        }
        if (!find) {
            return JsonMessage.getString(405, "删除失败");
        }
        JsonUtil.saveJson(filePath, jsonArray);
        //String newsJson = JsonUtil.formatJson(jsonArray.toString());
        //FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "");
    }
}
